package com.yourenbang.lingyun.transaction.util.bean;

import com.yourenbang.lingyun.domain.Merchant20;

import java.lang.reflect.Field;
import java.math.BigDecimal;

public class CombineBeans {

    /**
     * @Description: 该方法是用于相同对象不同属性值的合并，如果两个相同对象中同一属性都有值，
     *               那么sourceBean中的值会覆盖tagetBean重点的值
     * @param sourceBean
     *            被提取的对象bean
     * @param targetBean
     *            用于合并的对象bean
     * @return targetBean 合并后的对象
     * @return: Object
     */
    @SuppressWarnings("unused")
    public static Object combineSydwCore(Object sourceBean, Object targetBean) {
        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = sourceBeanClass.getDeclaredFields();
        for (int i = 0; i < sourceFields.length; i++) {
            Field sourceField = sourceFields[i];
            Field targetField = targetFields[i];
            sourceField.setAccessible(true);
            targetField.setAccessible(true);
            try {
                if (!(sourceField.get(sourceBean) == null)) {
                    targetField.set(targetBean, sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return targetBean;
    }

    public static void main(String[] args) {
        Merchant20 m1 = new Merchant20();
        m1.setUserBaseId("111");
        m1.setCityCode("222");
        m1.setPledgeCash(BigDecimal.TEN);

        Merchant20 m2 = new Merchant20();
       m2.setProvinceCode("AAA");
       m2.setUserBaseId("BBB");

       Merchant20 m3 = (Merchant20) CombineBeans.combineSydwCore(m2, m1);
        System.out.println(m3);
        // m2 覆盖 m1
        //Merchant20(userBaseId=BBB, provinceCode=AAA, cityCode=222, pledgeCash=10)
    }

}
